package it.polimi.TravelDream.ejb.eaos;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import it.polimi.TravelDream.ejb.dtos.PackageDTO;
import it.polimi.TravelDream.ejb.dtos.UserDTO;
import it.polimi.TravelDream.ejb.entities.BasicPackage;
import it.polimi.TravelDream.ejb.entities.Excursion;
import it.polimi.TravelDream.ejb.entities.Flight;
import it.polimi.TravelDream.ejb.entities.Room;
import it.polimi.TravelDream.ejb.entities.User;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class BasicPackageEAO
 */
@Stateless
public class BasicPackageEAO implements BasicPackageList {

	@PersistenceContext
	EntityManager em; 
	
	private List<Excursion> listExcursions = new ArrayList<Excursion>();
	private List<Flight> listFlights = new ArrayList<Flight>();
	private List<Room> listRoom = new ArrayList<Room>();
	BasicPackage newPackage = new BasicPackage();
	
    /**
     * Default constructor. 
     */
    public BasicPackageEAO() {}
    
    @Override
    public void createPackage(PackageDTO packageDTO, UserDTO userDTO){
    	newPackage = new BasicPackage(packageDTO);
    	
    	//Cerco le escursioni in base alla loro nazione
    	listExcursions = em.createNamedQuery(Excursion.FIND_EXCURSION_BY_NATION, Excursion.class).setParameter("nation", newPackage.getNation()).getResultList();
    	
    	//Aggiungo le escursioni in pacchetto e nei singoli voli il pacchetto
		for(Excursion e: listExcursions) {
			newPackage.getExcursions().add(e);
			e.getList_of_package().add(newPackage);
		}
    	
		//Aggiungo i voli in pacchetto e il pacchetto nei singoli voli
		for(Flight f: listFlights) {
			newPackage.getFlights().add(f);
			f.getList_of_package().add(newPackage);
		}
		
		//Aggiungo nel pacchetto le camere e nelle singole camere il pacchetto
		for(Room r: listRoom) {
			newPackage.getRooms().add(r);
			r.getList_of_package().add(newPackage);
		}

		newPackage.setEmployee(em.find(User.class, userDTO.getUsername()));
		
		em.persist(newPackage);
	}
    
    @Override
    public boolean checkFlight(Date startingDate, Date expirationDate, String city) {
    	listFlights = em.createNamedQuery(Flight.SEARCH_FLIGHTS_BY_PERIOD_AND_ARRIVAL_CITY, Flight.class)
				.setParameter("startingDate", startingDate).setParameter("expiringDate", expirationDate)
				.setParameter("arrivalCity", city).setParameter("departureCity", city).getResultList();
		
		if( listFlights.size() > 0 ) {
			return true;
		} else {
			return false;
		}
    }
    
    @Override
    public boolean checkRoom(String city, String nation) {

		listRoom = em.createNamedQuery(Room.FIND_ROOM_BY_CITY_AND_NATION, Room.class).setParameter("city", city).setParameter("nation", nation).getResultList();
		
		if( listRoom.size() > 0 ) {
			return true;
		} else {
			return false;
		}
    }

}
